package com.athena.framework.web;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.athena.util.SessionUtil;
import org.apache.catalina.Session;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import java.io.IOException;

public class RedisSessionHandlerValve extends ValveBase {

    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(RedisSessionHandlerValve.class);

    /**
     * redis-session-manager管理器操作
     */
    private RedisSessionManager manager;

    /**
     * 通过tomcat的context.xml可以注入该实例
     *
     * @param manager
     */
    public void setRedisSessionManager(RedisSessionManager manager) {
        this.manager = manager;
    }

    /**
     * 产生一个请求后
     */
    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("JSESSIONID")) {
                    sessionId = cookie.getValue();
                    break;
                }
            }
        }

        if (sessionId == null) {
            sessionId = request.getHeader("JSESSIONID");
        }

        if (sessionId == null) {
            Object tokenObj = request.getAttribute("token");
            if (tokenObj != null && tokenObj instanceof String) {
                String token = (String) tokenObj;
                if (StrUtil.isNotBlank(token)) {
                    sessionId = token;
                }
            }
        }

        if (StrUtil.isNotBlank(sessionId)) {
            request.setRequestedSessionId(sessionId);
        }

        try {
            getNext().invoke(request, response);
        } finally {

            // 删除内存中的session
            manager.afterRequest();
        }
    }
}
